const siteinfo  = require('../config');
const util      = require('util');
const md5       = require('md5')
const BASE_URL  = siteinfo.siteroot + '/';
const api_id    = siteinfo.api_id;
const api_secret= siteinfo.api_secret;
/*
* 签名认证
*/
const getSign = data => {
  let obj = {
    api_id:api_id,
    timestamp:Date.parse(new Date())/1000,
    nonce_str:parseInt(Math.random()*(999999-100000+1)+100000)
  }
  let keys  = Object.keys(obj).sort();
  let params = []
  keys.forEach(key => {
    params.push(key + '=' + util.trim(obj[key]))
  })
  params.push('key=' + api_secret)
	let paramStr = params.join('&')
  data.sign      = md5.md5(paramStr).toUpperCase();
  data.timestamp = obj.timestamp;
  data.nonce_str = obj.nonce_str;
  return data;
}
/**
 * 网络请求封装
 * @param url url路径名 例：/books
 * @param method 请求方式 POST/GET/DELETE等
 * @param data 请求参数 string类型
 * @param success  成功回调
 * @param fail 失败回调
 */
function request(url, method, data, success, fail) {
  if (!fail && !success && typeof data === 'function') {
    success = data;
    var data = getSign({})
  }else if (!fail) {
    if (typeof data === 'function') {
      fail = success
      success = data
      data = ""
    } else if (typeof data === 'object') {
      var data = getSign(data)
    } else {
      console.log("传递参数类型不正确");
    }
	}
	console.log( BASE_URL + url)
	console.log( data)
  var wxtask = wx.request({
    url: BASE_URL + url,
    header: {
        'content-type':'application/json',
        'yz-apiid':siteinfo.api_id,
        'yz-token':wx.getStorageSync('token'),
        'Cookie':'PHPSESSID='+ wx.getStorageSync('session_id'),  
    },
    method: method,
    data: data,
    success: function (res) {
      if (res.statusCode == 200){
        switch (res.data.code) {
          case 200: //请求成功
            success(res.data)
            break
          case 204: //成功请求空内容。
            success(res.data)
            break
          case 301: //永久跳转
            wx.showModal({
              content: res.data.message,showCancel: false,
              success: function (rel) {
                wx.redirectTo({url: res.data.url})
              }
            })
            break
          case 302: //临时跳转
            wx.showModal({
              content: res.data.message,
              success: function (rel) {
                if (rel.confirm) {
                  wx.navigateTo({url: res.data.url})
                }
              }
            })
            break
          case 303: //临时跳转
            wx.showModal({
              content: res.data.message,showCancel: false,
              success: function (rel) {
                if (rel.confirm) {
                  wx.switchTab({url: res.data.url})
                }
              }
            })
            break 
          case 307: //问答调整
            wx.showModal({
              content: res.data.message,
              cancelText:res.data.data.cancel,
              confirmText:res.data.data.confirm,
              success: function (rel) {
                if (rel.confirm) {
                  wx.navigateTo({url: res.data.url})
                }
              }
            })
            break
          case 403: //请求失败code弹出提示
            wx.showModal({content:res.data.message,showCancel:false})
            break
          case 404: //空也没后退
            wx.showModal({
              content: res.data.message,showCancel:false,
              success: function (rel) {
                wx.navigateBack({delta:1})
              }
            })
            break
          default:
            wx.showModal({content:res.data.message,showCancel:false})
            break
        }
      }else{
        if (fail) {
          fail(res)
        }
        wx.showModal({content:res.data.errMsg,showCancel:false})
      }
    },
    fail: function (res) {
      if (fail) {
        fail(res)
      }
    }
  })
  return wxtask;
}
/**
 * 请求封装-Get
 * @param url 请求地址
 * @param data 请求参数
 * @param success 成功回调
 * @param fail  失败回调
 * @constructor
 *
 * 返回值为微信请求实例   用于取消请求
 */
function Get(url, data, success, fail) {
  return new Promise((resolve, reject) => {
    return request(url,"GET", data, success, fail)
  })
}
/**
 * 请求封装-Post
 * @param url 请求地址
 * @param data 请求参数
 * @param success 成功回调
 * @param fail  失败回调
 * @constructor
 *
 * 返回值为微信请求实例   用于取消请求
 */
function Post(url, data, success, fail) {
  return new Promise((resolve, reject) => {
    return request(url,'POST', data, success, fail)
  })
}
/**
 * 请求封装-PUT
 * @param url 请求地址
 * @param data 请求参数
 * @param success 成功回调
 * @param fail  失败回调
 * @constructor
 *
 * 返回值为微信请求实例   用于取消请求
 */
function Put(url, data, success, fail) {
  return new Promise((resolve, reject) => {
    return request(url,'PUT', data, success, fail)
  })
}

/**
 * 请求封装-Delete
 * @param url 请求地址
 * @param data 请求参数
 * @param success 成功回调
 * @param fail  失败回调
 * @constructor
 *
 * 返回值为微信请求实例   用于取消请求
 */
function Delete(url, data, success, fail) {
  return new Promise((resolve, reject) => {
    return request(url,'DELETE', data, success, fail)
  })
}
/**
 * 图片上传
 * @param url 请求地址
 * @param data 请求参数
 * @param success 成功回调
 * @param fail  失败回调
 * @constructor
 * 返回值为微信请求实例
 */
function upload(url,tempPath, success, progress) {
  var uploadTask = wx.uploadFile({
    header: {
      'content-type':'application/x-www-form-urlencoded',
      'yz-apiid':siteinfo.api_id,
      'yz-token':wx.getStorageSync('token'),
      'Cookie':'PHPSESSID=' + wx.getStorageSync('session_id')
    },
    url: BASE_URL+url,
    filePath:tempPath,
    name:'file',
    success: function (res) {
      typeof success == "function" && success(JSON.parse(res.data))
    }
  })
  uploadTask.onProgressUpdate((res) => {
    typeof progress == "function" && progress({
      progress: res.progress
    })
  })
  return uploadTask;
}
exports.Get = Get;
exports.Post = Post;
exports.Put = Put;
exports.Delete = Delete;
exports.upload = upload;